package com.tsingteng.cosfun.ui.costar.publish;

import android.content.Intent;
import android.graphics.Bitmap;
import android.opengl.GLSurfaceView;
import android.os.Handler;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
import com.qiniu.pili.droid.shortvideo.PLCaptureFrameListener;
import com.qiniu.pili.droid.shortvideo.PLDisplayMode;
import com.qiniu.pili.droid.shortvideo.PLMediaFile;
import com.qiniu.pili.droid.shortvideo.PLShortVideoEditor;
import com.qiniu.pili.droid.shortvideo.PLShortVideoUploader;
import com.qiniu.pili.droid.shortvideo.PLUploadProgressListener;
import com.qiniu.pili.droid.shortvideo.PLUploadResultListener;
import com.qiniu.pili.droid.shortvideo.PLUploadSetting;
import com.qiniu.pili.droid.shortvideo.PLVideoEditSetting;
import com.qiniu.pili.droid.shortvideo.PLVideoFrame;
import com.qiniu.pili.droid.shortvideo.PLVideoSaveListener;
import com.tsingteng.cosfun.R;
import com.tsingteng.cosfun.app.AppContext;
import com.tsingteng.cosfun.base.BasePresenterActivity;
import com.tsingteng.cosfun.bean.JoinCostarBean;
import com.tsingteng.cosfun.bean.OpusBean;
import com.tsingteng.cosfun.bean.VideoSection;
import com.tsingteng.cosfun.bean.VideoSectionBean;
import com.tsingteng.cosfun.bean.VideoSignBean;
import com.tsingteng.cosfun.callback.AppListener;
import com.tsingteng.cosfun.callback.OnDBSaveListener;
import com.tsingteng.cosfun.common.Constant;
import com.tsingteng.cosfun.common.Navigate;
import com.tsingteng.cosfun.crashUtils.utils.LogUtil;
import com.tsingteng.cosfun.helper.ActivityManagers;
import com.tsingteng.cosfun.helper.VideoHelper;
import com.tsingteng.cosfun.ui.costar.VideoMusicFragment;
import com.tsingteng.cosfun.utils.BitmapUtils;
import com.tsingteng.cosfun.utils.DBUtils;
import com.tsingteng.cosfun.utils.FileUtil;
import com.tsingteng.cosfun.utils.FileUtils;
import com.tsingteng.cosfun.utils.LogUtils;
import com.tsingteng.cosfun.utils.ToastUtils;
import com.tsingteng.cosfun.utils.UIUtils;
import com.tsingteng.cosfun.widget.dialog.AudioMixSettingDialog;
import com.tsingteng.cosfun.widget.dialog.ProgressDialog;
import com.tsingteng.cosfun.widget.dialog.VideoSliceSelectDialog;
import com.tsingteng.cosfun.widget.dialog.VideoPulishDialog;


import org.json.JSONException;
import org.json.JSONObject;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;


/**
 * 描述: 发布页面
 * 创建人: 肖利
 * 时间: 2018/8/3
 * qq: (872179966)
 */


public class VideoPublishActivity extends BasePresenterActivity<VideoPublishPresenter, VideoContract.IVideoView> implements
        VideoContract.IVideoView, View.OnClickListener, VideoPulishDialog.OnVideoPublishDialogListener, PLVideoSaveListener, PLUploadResultListener,
        PLUploadProgressListener, PLCaptureFrameListener, VideoMusicFragment.OnDownVideoMusicListener, VideoSliceSelectDialog.OnDialogDissMissListener {


    private static final String TAG = "VideoPublishActivity";
    private ImageView mIvArrUp;
    private GLSurfaceView mPreview;
    private String videoPath;
    private Handler mHandler = new Handler();
    private PLMediaFile mMediaFile;
    private RelativeLayout mRlArrUp;
    private VideoPulishDialog videoPulishDialog;
    private Handler handler = new Handler();
    private PLShortVideoEditor mShortVideoEditor;
    private AudioMixSettingDialog mAudioMixSettingDialog;
    private boolean isAddMusic = false;

    private PLShortVideoUploader mVideoUploadManager;

    private JoinCostarBean joinCostarBean;
    private int upType = 0;//类型（用途）0：视频封面1：用户头：像2视频GIF图3：尬评视频4：完整视频5：视频片段
    private String upSign;
    private String upDomain;
    private String upPath;
    private int currentPosition = 0;
    private VideoMusicFragment videoMusicFragment;
    private boolean isStart = true;
    private ImageView mPlay;
    private ProgressDialog progressDialog;
    private int publishVideoSize = 0;
    private int havePublishVideo = 0;
    private ArrayList<String> deteleVideoUrl = new ArrayList<>();
    private LinearLayout mLlToolsRight;
    private int musicPosition = -1;
    private String musicUrl;
    private boolean gifSuccess = false;
    private boolean isUpLoading = false;//上传中
    private boolean isSaveing =false;//保存中

    @Override
    public void getIntentData(Intent intent) {
        isFullScreen = true;//设置全屏
        joinCostarBean = VideoHelper.getIntence().getJoinCostarBean();
        if (joinCostarBean == null){
            ToastUtils.showToast("请返回草稿箱重新发布!");
            finish();
            return;
        }
        videoPath = joinCostarBean.getLocalUrl();
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_publish_video;
    }


    @Override
    public void initData() {
        ActivityManagers.getInstance().addFoundActivity(this);
        mIvArrUp =  findViewById(R.id.iv_arrows_up);
        mRlArrUp =  findViewById(R.id.rl_arr_up);
        mPlay =  findViewById(R.id.iv_play);
        mLlToolsRight =  findViewById(R.id.ll_tools_right);
        mIvArrUp.setOnClickListener(this);
        mPreview =  findViewById(R.id.preview);
        LinearLayout mLlVolume =  findViewById(R.id.ll_volume);
        findViewById(R.id.ll_music).setOnClickListener(this);
        findViewById(R.id.iv_close).setOnClickListener(this);
        mPreview.setOnClickListener(this);

        mLlVolume.setOnClickListener(this);
        mMediaFile = new PLMediaFile(videoPath);
        PLVideoEditSetting setting = new PLVideoEditSetting();
        setting.setSourceFilepath(videoPath);
        setting.setDestFilepath(VideoHelper.EDITED_FILE_PATH);
        mShortVideoEditor = new PLShortVideoEditor(mPreview, setting);
        //初始化背景音乐dialog
        mAudioMixSettingDialog = new AudioMixSettingDialog();
        mShortVideoEditor.setVideoSaveListener(this);
        mShortVideoEditor.setDisplayMode(PLDisplayMode.FULL);
        //上传
        PLUploadSetting uploadSetting = new PLUploadSetting();
        mVideoUploadManager = new PLShortVideoUploader(AppContext.getContext(), uploadSetting);
        mVideoUploadManager.setUploadProgressListener(this);
        mVideoUploadManager.setUploadResultListener(this);
        //初始化发布dialog
        videoPulishDialog = new VideoPulishDialog(this);
        videoPulishDialog.setOnVideoPublishDialogDisMissListener(this);
        videoPulishDialog.show();
        progressDialog = new ProgressDialog(this);
        initMusic();
        videoMusicFragment = new VideoMusicFragment();
        videoMusicFragment.setOnDownVideoMusicListener(this);

        initBeanVideo();
        //将视屏信息保存到草稿,发布完成后自动回删除
        DBUtils.UpDataJoinBean(VideoHelper.getIntence().getVideoType(), VideoHelper.getIntence().getJoinCostarBean(), new OnDBSaveListener() {
            @Override
            public void onSaveSuccess() {

            }

            @Override
            public void onSaveFail() {

            }
        });
    }

    /**
     * 处理视屏
     */
    private void initBeanVideo() {

        //获取关键帧
        PLVideoFrame videoFrameByIndex = mMediaFile.getVideoFrameByIndex(0, false);
        if (null != videoFrameByIndex) {
            Bitmap bitmap = videoFrameByIndex.toBitmap();
            String picPath = BitmapUtils.saveBitmap(bitmap);
            joinCostarBean.setVideoCverUrl(picPath);
        }
        if (!TextUtils.isEmpty(joinCostarBean.getMusicUrl())) {
            mShortVideoEditor.setAudioMixFile(joinCostarBean.getMusicUrl());
        }
        Gson gson = new Gson();
        System.out.println("joinCostarBean" + gson.toJson(joinCostarBean));

    }

    @Override
    protected VideoPublishPresenter createPresenter() {
        return new VideoPublishPresenter();
    }

    /**
     * 启动预览
     */
    private PLShortVideoEditorStatus mShortVideoEditorStatus = PLShortVideoEditorStatus.Idle;

    private void startPlayback() {
        mPlay.setVisibility(View.GONE);
        if (mShortVideoEditorStatus == PLShortVideoEditorStatus.Idle) {
            mShortVideoEditor.startPlayback();
            mShortVideoEditorStatus = PLShortVideoEditorStatus.Playing;
        } else if (mShortVideoEditorStatus == PLShortVideoEditorStatus.Paused) {
            mShortVideoEditor.resumePlayback();
            mShortVideoEditorStatus = PLShortVideoEditorStatus.Playing;
        }
    }

    /**
     * 暂停预览
     */
    private void pausePlayback(boolean isClick) {
        if (isClick)
            mPlay.setVisibility(View.VISIBLE);
        mShortVideoEditor.pausePlayback();
        mShortVideoEditorStatus = PLShortVideoEditorStatus.Paused;
    }

    /**
     * 停止预览
     */
    private void stopPlayback(boolean isClick) {
        mShortVideoEditor.stopPlayback();
        if (isClick)
            mPlay.setVisibility(View.VISIBLE);
        mShortVideoEditorStatus = PLShortVideoEditorStatus.Idle;
    }

    private void initMusic() {
        mAudioMixSettingDialog = new AudioMixSettingDialog();
        // make dialog create +
        mAudioMixSettingDialog.show(getSupportFragmentManager(), "");
        mAudioMixSettingDialog.dismiss();
        // make dialog create -
        mAudioMixSettingDialog.setOnAudioVolumeChangedListener(mOnAudioVolumeChangedListener);
        mAudioMixSettingDialog.setOnAudioMixSettingDialogDissMiss(new AudioMixSettingDialog.OnAudioMixSettingDialogDissMiss() {
            @Override
            public void onDismiss() {
                mLlToolsRight.setVisibility(View.VISIBLE);
                mAudioMixSettingDialog.dismiss();
            }
        });
        mAudioMixSettingDialog.setCancelable(false);

    }


    private AudioMixSettingDialog.OnAudioVolumeChangedListener mOnAudioVolumeChangedListener = new AudioMixSettingDialog.OnAudioVolumeChangedListener() {
        @Override
        public void onAudioVolumeChanged(int fgVolume, int bgVolume) {
            LogUtils.d("fg volume: " + fgVolume + " bg volume: " + bgVolume);
            mShortVideoEditor.setAudioMixVolume(fgVolume / 100f, bgVolume / 100f);
        }
    };


    private void stopTrackPlayProgress() {
        mHandler.removeCallbacksAndMessages(null);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_arrows_up:
                mRlArrUp.setVisibility(View.GONE);
                videoPulishDialog.show();
                break;

            case R.id.ll_volume:
                mAudioMixSettingDialog.show(getSupportFragmentManager(), "");
                mLlToolsRight.setVisibility(View.GONE);
                break;
            case R.id.ll_music:
                if (videoMusicFragment == null) videoMusicFragment = new VideoMusicFragment();
                videoMusicFragment.setMusicPosition(musicPosition);
                videoMusicFragment.show(getSupportFragmentManager(), "music");
                pausePlayback(true);
                break;
            case R.id.iv_close:
                finish();
                break;
            case R.id.preview:
                if (isStart) {
                    pausePlayback(true);
                } else {
                    startPlayback();
                }
                isStart = !isStart;
                break;

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        startPlayback();
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopTrackPlayProgress();
        pausePlayback(false);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopPlayback(false);
        if (mMediaFile != null) {
            mMediaFile.release();
        }
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
        if (mShortVideoEditor != null) {
            mShortVideoEditor.pausePlayback();
        }
    }

    @Override
    public void onDissMiss() {
        handler.postDelayed(() -> mRlArrUp.setVisibility(View.VISIBLE), 500);

    }

    @Override
    public void onPublish() {
        if (videoPulishDialog != null) videoPulishDialog.dissMiss();
        if (isAddMusic) {
            if (progressDialog == null) progressDialog = new ProgressDialog(this);
            progressDialog.show();
            mShortVideoEditor.save();
            isSaveing = true;
        } else {
            starUploadVideo();
        }

    }


    @Override
    public void showFail(String msg) {
        super.showFail(msg);
        if (progressDialog != null) {
            progressDialog.disMissDialog();
        }
    }

    private void starUploadVideo() {
        isUpLoading = true;
        //将所有的视屏地址保存到一个集合中,上传完成后删除
        if (deteleVideoUrl == null) deteleVideoUrl = new ArrayList<>();
        deteleVideoUrl.clear();
        deteleVideoUrl.addAll(VideoHelper.getIntence().getVideoPathList());
        deteleVideoUrl.add(joinCostarBean.getLocalUrl());
        LogUtils.e(TAG, "將所有的视屏添加到了一个集合中,上传完成后删除,数量大小为" + deteleVideoUrl.size());
        List<VideoSectionBean> videoSectionInfos = joinCostarBean.getVideoSectionInfos();
        publishVideoSize = videoSectionInfos.size();
        if (publishVideoSize <= 0) return;
        if (TextUtils.isEmpty(joinCostarBean.getVideoGifUrl())) {
            publishVideoSize = publishVideoSize + 3;//上传的次数 加一次封面  和一次主视频
        } else {
            publishVideoSize = publishVideoSize + 2;//上传的次数 加一次封面  和一次主视频
        }
        String titleText = videoPulishDialog.getTitleText();
        joinCostarBean.setVideoDesp(titleText);
        if (progressDialog == null) progressDialog = new ProgressDialog(this);
        progressDialog.show();
        ToastUtils.showToast("正在发布中,请耐心等候!");
        upType = 4;
        mPresenter.getSignTureData(upType);
    }



    @Override
    public void onDrafts() {
        //将视屏保存到数据库中
//        boolean b = DBUtils. saveShootVideo(joinCostarBean.getVideoUrl(), joinCostarBean.getCreateTime(), true, VideoUtils.getIntance().getVideoType(),joinCostarBean.getVideoCverUrl());
        if (isAddMusic) {
            joinCostarBean.setMusicUrl(musicUrl);
        }
        saveDrafts();
    }

    private void saveDrafts() {
        DBUtils.UpDataJoinBean(VideoHelper.getIntence().getVideoType(), VideoHelper.getIntence().getJoinCostarBean(), new OnDBSaveListener() {
            @Override
            public void onSaveSuccess() {
                showHintDialog("保存草稿成功!");
                VideoHelper.getIntence().destroyVideoList();
                ActivityManagers.getInstance().delShootActivity();
                ActivityManagers.getInstance().finishToMainActivity();
            }

            @Override
            public void onSaveFail() {
                showHintDialog("保存草稿失败!");
            }
        });
    }

    @Override
    public void onSaveVideoSuccess(String s) {

        UIUtils.runOnUIThread(() -> {
            isSaveing = true;
//            joinCostarBean.setVideoUrl(s);
            isAddMusic = false;
           starUploadVideo();
        });
    }

    @Override
    public void onSaveVideoFailed(int i) {
      UIUtils.runOnUIThread(() -> {
          isSaveing = false;
          showToast("保存失败!");
          progressDialog.disMissDialog();
      });
    }

    @Override
    public void onSaveVideoCanceled() {
      UIUtils.runOnUIThread(() -> {
          isSaveing = false;
          showToast("保存取消!");
          progressDialog.disMissDialog();
      });
    }

    @Override
    public void onProgressUpdate(float percentage) {
        UIUtils.runOnUIThread(() -> {
            LogUtils.e(TAG, "percentage");
            progressDialog.setmProgressbar((int) (100 * percentage));
        });

    }


    @Override
    public void UploadVideo(VideoSignBean data) {
        upLoad(data);
    }

    public void upLoad(VideoSignBean data) {
        upSign = data.getSign();
        upDomain = data.getDomain();
        upPath = data.getPath();
        if (upType == 0) {
            if (isUpQiNiu(joinCostarBean.getVideoCverUrl())) {
                if (!TextUtils.isEmpty(joinCostarBean.getVideoGifUrl())) {
                    upType = 2;
                    mPresenter.getSignTureData(upType);
                } else {
                    upVideo();
                }
            }else {
                mVideoUploadManager.startUpload(joinCostarBean.getVideoCverUrl(), upPath + "/" + FileUtils.getFileNameMD5(joinCostarBean.getVideoCverUrl()) + ".jpg", upSign);
            }
        }
        if (upType == 2) {
            if (isUpQiNiu(joinCostarBean.getVideoGifUrl())) {
                upVideo();
            }else {
                mVideoUploadManager.startUpload(joinCostarBean.getVideoGifUrl(), upPath + "/" + FileUtils.getFileNameMD5(joinCostarBean.getVideoGifUrl()) + ".gif", upSign);
            }
        }
        if (upType == 4) {
            if (isUpQiNiu(joinCostarBean.getVideoUrl())) {
                //说明已经上传过主视频:直接上传分段视屏
                upType =5;
                mPresenter.getSignTureData(upType);
            }else {
                mVideoUploadManager.startUpload(joinCostarBean.getLocalUrl(), upPath + "/" + FileUtils.getFileNameMD5(joinCostarBean.getLocalUrl()) + ".mp4", upSign);
            }
        }
        if (upType == 5) {
            if (isUpQiNiu(joinCostarBean.getVideoSectionInfos().get(currentPosition).getSectionVideoUrl())) {
                if (currentPosition<joinCostarBean.getVideoSectionInfos().size()-1) {
                    currentPosition++;
                    upLoad(data);
                }else {
                    upCoverVideo();
                }
            }else {
                mVideoUploadManager.startUpload(joinCostarBean.getVideoSectionInfos().get(currentPosition).getLocalUrl(), upPath + "/" +FileUtils. getFileNameMD5(joinCostarBean.getVideoSectionInfos().get(currentPosition).getLocalUrl()) + ".mp4", upSign);
            }
        }
    }


    @Override
    public void showPublishVideo(OpusBean opusBean) {
        //销毁videoHelper和保存数据库的视屏
        VideoHelper.getIntence().destroyVideoList();
        DBUtils.deleteJoinBean(VideoHelper.getIntence().getVideoType(), new OnDBSaveListener() {
            @Override
            public void onSaveSuccess() {

            }
            @Override
            public void onSaveFail() {

            }
        });
        for (int i = 0; i < deteleVideoUrl.size(); i++) {
            boolean deteleFile = FileUtil.deleteFile(deteleVideoUrl.get(i));
            if (deteleFile) {
                LogUtils.e(TAG, "删除成功!" + deteleVideoUrl.get(i));
            } else {
                LogUtils.e(TAG, "删除失败!" + deteleVideoUrl.get(i));
            }
        }
        OpusBean mOpusBean = VideoHelper.getIntence().getmOpusBean();
        if (null !=mOpusBean){
            for (int j =0;j<opusBean.getVideoSectionInfoList().size();j++) {
                VideoSection mVideoSection = opusBean.getVideoSectionInfoList().get(j);
                for (int i = 0; i < mOpusBean.getVideoSectionInfoList().size(); i++) {
                    VideoSection videoSection = mOpusBean.getVideoSectionInfoList().get(i);
                    if (mVideoSection.getCostarProfileId() == videoSection.getCostarProfileId()){
                        mVideoSection.setIsAttentionCostar(videoSection.getIsAttentionCostar());
                    }
                }
            }
        }
        if (!TextUtils.equals(opusBean.getIsActivity(), "1")) {
            ActivityManagers.getInstance().deleteFoundActivity();
            int alwaysFinish = Settings.Global.getInt(getContentResolver(), Settings.Global.ALWAYS_FINISH_ACTIVITIES, 0);
            if (1 == alwaysFinish) {
                Navigate.gotoMainActivity(VideoPublishActivity.this);
                return;
            }else{
                ActivityManagers.getInstance().delShootActivity();
                ActivityManagers.getInstance().finishToMainActivity();
                new Handler().postDelayed(() -> {
                    //发布成功,播放发布视屏的回调
                    videoBack(opusBean);
                    finish();
                }, 500);
                return;
            }
        }
        videoBack(opusBean);
        Navigate.gotoJoinDone(this);
    }

    void videoBack(OpusBean opusBean) {
        AppListener.OnPublishVideoBackListener onPublishVideoBackListener = AppListener.getInstance().getOnPublishVideoBackListener();
        if (onPublishVideoBackListener!=null) {
            onPublishVideoBackListener.OnVideoBack(opusBean);
        }
    }

    @Override
    public void onUploadProgress(String fileName, double percent) {
        runOnUiThread(() -> {
            if (publishVideoSize<=0) {
            }else {
                LogUtils.e(TAG, "percentage" + percent);
                progressDialog.setmProgressbar(havePublishVideo * 100 / publishVideoSize);
            }


        });
    }


    @Override
    public void onUploadVideoSuccess(JSONObject response) {
        try {
            havePublishVideo++;
            final String filePath = upDomain + "/" + response.getString("key");
            runOnUiThread(() -> {
                if (upType == 0) {
                    joinCostarBean.setVideoCverUrl(filePath);
//
                    if (!TextUtils.isEmpty(joinCostarBean.getVideoGifUrl())) {
                        upType = 2;
                        mPresenter.getSignTureData(upType);
                    } else {
                        upVideo();
                    }
                    return;
                }

                if (upType == 2) {
                    joinCostarBean.setVideoGifUrl(filePath);
                    upVideo();
                    return;
                }

                if (upType == 4) {
//                        LogUtils.e(TAG,"上传完删除主视屏"+ joinCostarBean.getVideoSectionInfos().get(currentPosition).getSectionVideoUrl()+ "isDelete" + deteleFile);
                    joinCostarBean.setVideoUrl(filePath);
                    upType = 5;
                    mPresenter.getSignTureData(upType);
                    return;
                }

                if (upType == 5) {
//                        boolean deteleFile = FileUtils.deteleFile(joinCostarBean.getVideoSectionInfos().get(currentPosition).getSectionVideoUrl());
//                        LogUtils.e(TAG,"上传完删除视屏片段"+ joinCostarBean.getVideoSectionInfos().get(currentPosition).getSectionVideoUrl()+ "isDelete" + deteleFile);
                    joinCostarBean.getVideoSectionInfos().get(currentPosition).setSectionVideoUrl(filePath);

                    if (currentPosition == joinCostarBean.getVideoSectionCount() - 1) {//地址都已经得到
                        //执行上传的逻辑
                        upCoverVideo();
                        return;
                    }
                    currentPosition++;
                    FileInputStream fileInputStream = null;
                    try {
                        fileInputStream = new FileInputStream(joinCostarBean.getVideoSectionInfos().get(currentPosition).getLocalUrl());
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                    String fileName = FileUtils.getFileMD5(fileInputStream);
                    mVideoUploadManager.startUpload(joinCostarBean.getVideoSectionInfos().get(currentPosition).getLocalUrl(), upPath + "/" + fileName + ".mp4", upSign);
//                        mVideoUploadManager.startUpload( joinCostarBean.getVideoSectionInfos().get(currentPosition).getSectionVideoUrl(), String.valueOf(LogonUtils.getProFildId()+System.currentTimeMillis()).hashCode()+upPath,upSign);
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void upCoverVideo() {
        //上传封面
        upType = 0;
        mPresenter.getSignTureData(upType);
    }

    private void upVideo() {
        Gson gson = new Gson();
        long activityId = VideoHelper.getIntence().getActivityId();
        if (-1 != activityId) {
            String title ;
            String isActivity;
            OpusBean opusBean = VideoHelper.getIntence().getmOpusBean();
            if (null ==opusBean){
                JoinCostarBean joinCostarBean = VideoHelper.getIntence().getmJoinCostarBean();
                title = joinCostarBean.getActivityTitle();
                isActivity = joinCostarBean.getIsActivity();
            }else{
               title = opusBean.getActivityTitle();
               isActivity = opusBean.getIsActivity();
            }
            joinCostarBean.setActivityId(activityId);
            joinCostarBean.setActivityTitle(title);
            joinCostarBean.setIsActivity(isActivity);
        }
//        else {
//            joinCostarBean.setActivityId(0);
//            joinCostarBean.setActivityTitle("");
//            joinCostarBean.setIsActivity("2");
//        }
        String s = gson.toJson(joinCostarBean);
        System.out.println("文件上传成功" + s);
        publishVideoSize = 0;
        havePublishVideo = 0;
        progressDialog.disMissDialog();
        //发布成功
        mPresenter.getPublishVideo(VideoHelper.getIntence().getPlayId() == -1 ? "" : String.valueOf(VideoHelper.getIntence().getPlayId()), s);
    }

    @Override
    public void onUploadVideoFailed(int statusCode, String error) {
        isUpLoading = false;
        runOnUiThread(() -> {
            currentPosition = 0;//上传失败后将索引归结为0
            showToast("网络错误,请重新上传!");
            LogUtils.i(TAG,statusCode + "statusCode"+ error+ "statusCode");
            progressDialog.disMissDialog();
        });
    }

    @Override
    public void onFrameCaptured(PLVideoFrame plVideoFrame) {

    }

    @Override
    public void selectMusic(int currentPosition, String musicUrl) {
        this.musicPosition = currentPosition;
        this.musicUrl = musicUrl;
        mShortVideoEditor.setAudioMixFile(null);
        isAddMusic = true;
        if (TextUtils.isEmpty(musicUrl)) return;
        new Handler().postDelayed(() -> {
            mShortVideoEditor.setAudioMixFile(musicUrl);
            startPlayback();
        }, 100);
    }

    @Override
    public void dissFragmentDialog() {
        videoMusicFragment.dismiss();
        startPlayback();
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case Constant.REQUESTCODE:
                    setResult(RESULT_OK);
                    finish();
                    break;
            }
        }
    }


    // 视频编辑器预览状态
    private enum PLShortVideoEditorStatus {
        Idle,
        Playing,
        Paused,
    }


    private boolean isUpQiNiu(String videoPath) {
        if (TextUtils.isEmpty(videoPath)) return false;
        if (videoPath.contains(VideoHelper.QINIU_HOST)) return true;
        return false;
    }
}
